package com.sicong.authentication.service;

import com.sicong.admin.dto.UserInfo;
import com.sicong.admin.feign.RemoteUserService;
import com.sicong.common.core.constants.SecurityConstants;
import com.sicong.common.core.enums.ResultEnum;
import com.sicong.common.core.utils.Result;
import com.sicong.common.security.entity.SecurityUser;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author chenww
 * @date 2020-11-25
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final RemoteUserService remoteUserService;

    private final CacheManager cacheManager;

    @Autowired
    public UserDetailsServiceImpl(RemoteUserService remoteUserService,
                                  CacheManager cacheManager) {
        this.remoteUserService = remoteUserService;
        this.cacheManager = cacheManager;
    }

    /**
     * 用户密码登录
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null) {
            UserInfo userInfo = (UserInfo) cache.get(username).get();
            return getUserDetails(userInfo);
        }
        Result<UserInfo> result = remoteUserService.info(username, SecurityConstants.SECURITY_INNER);
        if (result.getCode() == ResultEnum.ACCOUNT_NOT_EXIST.getCode()) {
            throw new UsernameNotFoundException(ResultEnum.ACCOUNT_NOT_EXIST.getMsg());
        }
        cache.put(username, result.getData());
        return getUserDetails(result.getData());
    }

    private SecurityUser getUserDetails(UserInfo userInfo) {
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUsername(userInfo.getUser().getUsername());
        securityUser.setPassword(userInfo.getUser().getPassword());
        securityUser.setPermissions(userInfo.getPermissions());
        return securityUser;
    }

}
